const { classApi } = require('../../../utils/api');

Page({
  data: {
    classes: [],
    filteredClasses: [],
    loading: false,
    error: null,
    searchKeyword: '',
    currentFilter: 'all',
    currentUserId: 1, // 这里应该从用户登录信息中获取
    classStats: {
      totalClasses: 0,
      myClasses: 0,
      headteacherClasses: 0
    }
  },

  onLoad() {
    this.loadClasses();
  },

  onShow() {
    // 页面显示时刷新数据
    this.loadClasses();
  },

  // 加载班级列表
  async loadClasses() {
    this.setData({ loading: true, error: null });
    
    try {
      const response = await classApi.getAllClasses();
      console.log('获取班级列表API响应:', response);
      
      // 处理新的Result格式响应
      let classes = [];
      if (response && response.code === 200 && response.data) {
        classes = response.data;
      } else if (Array.isArray(response)) {
        // 兼容旧格式
        classes = response;
      } else {
        throw new Error(response.message || 'API返回数据格式错误');
      }
      
      console.log('解析后的班级数据:', classes);
      
      // 处理班级数据，添加格式化时间等
      const processedClasses = classes.map(classItem => ({
        ...classItem,
        formattedTime: this.formatTime(classItem.createTime),
        // 确保必要字段存在
        className: classItem.className || '未命名班级',
        grade: classItem.grade || '未知年级',
        subject: classItem.subject || '未知科目',
        classCode: classItem.classCode || '无邀请码',
        isHeadteacher: classItem.isHeadteacher || 0,
        creatorUserId: classItem.creatorUserId || 0
      }));
      
      console.log('处理后的班级数据:', processedClasses);
      
      // 计算班级统计
      const classStats = this.calculateClassStats(processedClasses);
      
      this.setData({ 
        classes: processedClasses,
        filteredClasses: processedClasses,
        classStats: classStats,
        loading: false 
      });
      
      // 应用当前筛选
      this.applyFilter();
      
      wx.showToast({
        title: `加载成功，共${processedClasses.length}个班级`,
        icon: 'success',
        duration: 1500
      });
    } catch (error) {
      console.error('获取班级列表失败:', error);
      this.setData({ 
        error: '加载失败，请重试',
        loading: false 
      });
      
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      });
    }
  },

  // 计算班级统计
  calculateClassStats(classes) {
    const stats = {
      totalClasses: classes.length,
      myClasses: 0,
      headteacherClasses: 0
    };
    
    classes.forEach(classItem => {
      if (classItem.creatorUserId === this.data.currentUserId) {
        stats.myClasses++;
      }
      if (classItem.isHeadteacher === 1) {
        stats.headteacherClasses++;
      }
    });
    
    console.log('班级统计:', stats);
    return stats;
  },

  // 格式化时间
  formatTime(dateString) {
    if (!dateString) return '';
    
    const date = new Date(dateString);
    const now = new Date();
    const diff = now - date;
    
    // 小于1分钟
    if (diff < 60000) {
      return '刚刚';
    }
    // 小于1小时
    if (diff < 3600000) {
      return Math.floor(diff / 60000) + '分钟前';
    }
    // 小于1天
    if (diff < 86400000) {
      return Math.floor(diff / 3600000) + '小时前';
    }
    // 小于7天
    if (diff < 604800000) {
      return Math.floor(diff / 86400000) + '天前';
    }
    
    // 超过7天显示具体日期
    return date.toLocaleDateString();
  },

  // 搜索输入
  onSearchInput(e) {
    const keyword = e.detail.value;
    this.setData({ searchKeyword: keyword });
    this.applyFilter();
  },

  // 清除搜索
  clearSearch() {
    this.setData({ searchKeyword: '' });
    this.applyFilter();
  },

  // 筛选切换
  onFilterChange(e) {
    const filter = e.currentTarget.dataset.filter;
    this.setData({ currentFilter: filter });
    this.applyFilter();
  },

  // 应用筛选
  applyFilter() {
    const { classes, searchKeyword, currentFilter } = this.data;
    let filtered = [...classes];

    // 搜索筛选
    if (searchKeyword) {
      const keyword = searchKeyword.toLowerCase();
      filtered = filtered.filter(classItem => 
        classItem.className.toLowerCase().includes(keyword) ||
        classItem.grade.toLowerCase().includes(keyword) ||
        classItem.subject.toLowerCase().includes(keyword)
      );
    }

    // 类型筛选
    if (currentFilter === 'my') {
      filtered = filtered.filter(classItem => classItem.creatorUserId === this.data.currentUserId);
    } else if (currentFilter === 'headteacher') {
      filtered = filtered.filter(classItem => classItem.isHeadteacher === 1);
    }

    // 按时间排序
    filtered.sort((a, b) => new Date(b.createTime) - new Date(a.createTime));

    this.setData({ filteredClasses: filtered });
  },

  // 点击班级项
  onClassTap(e) {
    const classId = e.currentTarget.dataset.classId;
    console.log('点击班级ID:', classId);
    
    // 根据classId找到对应的班级信息
    const classItem = this.data.filteredClasses.find(item => item.classId == classId);
    
    if (!classItem) {
      console.error('未找到对应的班级信息');
      wx.showToast({
        title: '班级信息不存在',
        icon: 'none'
      });
      return;
    }
    
    console.log('班级信息:', classItem);
    
    // 显示班级详情
    wx.showModal({
      title: classItem.className,
      content: `年级：${classItem.grade}\n科目：${classItem.subject}\n邀请码：${classItem.classCode}`,
      showCancel: false,
      confirmText: '知道了'
    });
  },

  // 创建班级
  createClass() {
    wx.navigateTo({
      url: '/pages/class/create-class/index'
    });
  },

  // 编辑班级
  editClass(e) {
    const classId = e.currentTarget.dataset.classId;
    console.log('编辑班级ID:', classId);
    
    // 根据classId找到对应的班级信息
    const classItem = this.data.filteredClasses.find(item => item.classId == classId);
    
    if (!classItem) {
      console.error('未找到对应的班级信息');
      wx.showToast({
        title: '班级信息不存在',
        icon: 'none'
      });
      return;
    }
    
    console.log('编辑班级:', classItem);
    
    // 跳转到编辑班级页面
    wx.navigateTo({
      url: `/pages/class/create-class/index?mode=edit&classId=${classId}&className=${encodeURIComponent(classItem.className)}&grade=${encodeURIComponent(classItem.grade)}&subject=${encodeURIComponent(classItem.subject)}&classCode=${encodeURIComponent(classItem.classCode)}`
    });
  },

  // 删除班级
  deleteClass(e) {
    const classId = e.currentTarget.dataset.classId;
    console.log('删除班级ID:', classId);
    
    // 根据classId找到对应的班级信息
    const classItem = this.data.filteredClasses.find(item => item.classId == classId);
    
    if (!classItem) {
      console.error('未找到对应的班级信息');
      wx.showToast({
        title: '班级信息不存在',
        icon: 'none'
      });
      return;
    }
    
    console.log('删除班级:', classItem);
    
    wx.showModal({
      title: '确认删除',
      content: `确定要删除班级"${classItem.className}"吗？`,
      success: (res) => {
        if (res.confirm) {
          this.confirmDelete(classItem);
        }
      }
    });
  },

  // 确认删除
  async confirmDelete(classItem) {
    try {
      wx.showLoading({ title: '删除中...' });
      
      const response = await classApi.deleteClass(classItem.classId);
      console.log('删除班级API响应:', response);
      
      wx.hideLoading();
      
      // 处理新的Result格式响应
      if (response && response.code === 200) {
        wx.showToast({
          title: '删除成功',
          icon: 'success'
        });
        // 重新加载数据
        this.loadClasses();
      } else {
        wx.showToast({
          title: response.message || '删除失败',
          icon: 'none'
        });
      }
    } catch (error) {
      wx.hideLoading();
      console.error('删除班级失败:', error);
      wx.showToast({
        title: '删除失败',
        icon: 'none'
      });
    }
  },

  // 查看班级成员
  viewClassMembers(e) {
    const classId = e.currentTarget.dataset.classId;
    console.log('查看班级成员，班级ID:', classId);
    
    // 根据classId找到对应的班级信息
    const classItem = this.data.filteredClasses.find(item => item.classId == classId);
    
    if (!classItem) {
      console.error('未找到对应的班级信息');
      wx.showToast({
        title: '班级信息不存在',
        icon: 'none'
      });
      return;
    }
    
    // 跳转到班级成员页面
    wx.navigateTo({
      url: `/pages/class/class-members/index?classId=${classId}&className=${encodeURIComponent(classItem.className)}`
    });
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.loadClasses().then(() => {
      wx.stopPullDownRefresh();
    });
  }
});
